package cn.com.inossem.operation;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.model.MessageInfoBean;
import cn.com.inossem.network.NetworkConnect;
import cn.com.inossem.requestmanager.WooRequestFactory;

import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class GetMessageOperation implements Operation {

	public static final String GETMESSAGE_OPERATION_NUM = "getmessage_operation_num";

	public Bundle bundle;

	@Override
	public Bundle execute(Context arg0, Request request)
			throws ConnectionException, DataException, CustomRequestException {
		String num = request.getString(GETMESSAGE_OPERATION_NUM);

		NetworkConnect connection = new NetworkConnect(WSConfig.LOCAL_URL
				+ "userInfo/listMessage");
		connection.setPostText("{\"useType\":\"" + "ALL" + "\",\"pageNum\":\""
				+ num + "\"}");
		System.out.println("{\"useType\":\"" + "ALL" + "\",\"pageNum\":\""
				+ num + "\"}");
		String body = connection.execute();

		System.out.println("GetMessageOperation:" + body);
		bundle = new Bundle();
		List<MessageInfoBean> retList;
		try {
			JSONObject jsonObject = new JSONObject(body);

			int errorFlag = jsonObject.getInt("errorFlag");
			if (errorFlag == WSConfig.RESULT_SUCESS) {
				Gson datagson = new Gson();
				String text = jsonObject.getString("messageList");
				retList = datagson.fromJson(text,
						new TypeToken<List<MessageInfoBean>>() {
						}.getType());
				bundle.putParcelableArrayList(
						WooRequestFactory.BUNDLE_EXTRA_MESSAGELIST,
						(ArrayList<? extends Parcelable>) retList);
			}
			bundle.putInt(WooRequestFactory.BUNDLE_EXTRA_SUCCESS, errorFlag);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return bundle;
	}
}
